'use client';

import React, { useState, useEffect } from 'react';
import { useSession } from 'next-auth/react';
import { useRouter } from 'next/navigation';
import Image from 'next/image';
import AppHeader from '@/components/ui/app-header';
import { UserProfile } from '@/types/user';
import { UserIcon, SwatchIcon } from '@heroicons/react/24/outline';
import { userApi } from '@/lib/api';
import ProfileDialog from '@/components/ui/profile-dialog';
import ThemeSelector from '@/components/ui/theme-selector';
import { useTheme, ThemeColor } from '@/hooks/use-theme';
import { Card } from '@/components/ui/card';

export default function ProfilePage() {
  const { data: session, status } = useSession();
  const router = useRouter();
  const { themeColor, setThemeColor } = useTheme();
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [userProfile, setUserProfile] = useState<UserProfile | null>(null);
  const [isProfileDialogOpen, setIsProfileDialogOpen] = useState(false);
  const [showThemeSelector, setShowThemeSelector] = useState(false);
  const [savingTheme, setSavingTheme] = useState(false);
  const [themeMessage, setThemeMessage] = useState<{ type: 'success' | 'error' | ''; text: string }>({ type: '', text: '' });

  useEffect(() => {
    // 如果用户未登录，重定向到登录页面
    if (status === 'unauthenticated') {
      router.push('/auth/login');
      return;
    }

    // 如果用户已登录，获取用户资料
    if (status === 'authenticated' && session?.user?.id) {
      fetchUserProfile(session.user.id);
    }
  }, [status, session, router]);

  // 获取用户资料
  const fetchUserProfile = async (userId: string) => {
    try {
      setLoading(true);
      const profile = await userApi.getUserProfile(userId);
      setUserProfile(profile);
      setError(null);
    } catch (err) {
      console.error('获取用户资料失败:', err);
      setError('无法加载用户资料，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  // 处理保存个人资料
  const handleSaveProfile = async (updatedProfile: UserProfile) => {
    try {
      await updateProfile(updatedProfile);
      // 更新成功后刷新页面数据
      if (session?.user?.id) {
        await fetchUserProfile(session.user.id);
      }
    } catch (err) {
      console.error('保存个人资料失败:', err);
      throw err;
    }
  };

  // 调用API更新个人资料
  const updateProfile = async (profile: UserProfile) => {
    try {
      await userApi.updateUserProfile(profile);
    } catch (err) {
      console.error('更新个人资料失败:', err);
      throw err;
    }
  };

  // 切换主题颜色并保存设置
  const handleThemeColorChange = async (color: ThemeColor) => {
    try {
      setSavingTheme(true);
      setThemeMessage({ type: '', text: '' });
      
      // 立即更新本地主题颜色
      setThemeColor(color);
      
      // 保存到服务器
      await userApi.updateThemeSettings('system', color);
      
      // 显示成功消息
      setThemeMessage({ type: 'success', text: '主题颜色已更新' });
      
      // 短暂显示后关闭选择器和消息
      setTimeout(() => {
        setThemeMessage({ type: '', text: '' });
        setShowThemeSelector(false);
      }, 2000);
    } catch (error) {
      console.error('更新主题颜色失败:', error);
      setThemeMessage({ 
        type: 'error', 
        text: error instanceof Error ? error.message : '更新主题颜色失败'
      });
    } finally {
      setSavingTheme(false);
    }
  };

  // 加载状态
  if (status === 'loading' || loading) {
    return (
      <div className="container mx-auto py-8 px-4">
        <div className="text-center">
          <h2 className="text-xl font-semibold">正在加载...</h2>
          <p className="mt-2">请稍候</p>
        </div>
      </div>
    );
  }

  // 错误状态
  if (error || !userProfile) {
    return (
      <div className="container mx-auto py-8 px-4">
        <div className="text-center">
          <h2 className="text-xl font-semibold">出现错误</h2>
          <p className="mt-2">{error || '未找到用户资料'}</p>
          <button 
            onClick={() => router.refresh()}
            className="mt-4 px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
          >
            刷新页面
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8 px-4">
      <AppHeader title="个人资料" subtitle="查看和管理您的个人信息" />
      <div className="bg-white shadow-md rounded-lg overflow-hidden max-w-4xl mx-auto mt-6">
        <div className="p-6 md:p-8">
          {/* 头部信息 */}
          <div className="flex flex-col md:flex-row items-center gap-6">
            <div className="relative w-32 h-32 rounded-full overflow-hidden bg-gray-100">
              {userProfile.image ? (
                <Image
                  src={userProfile.image}
                  alt={userProfile.name || '用户头像'}
                  fill
                  className="object-cover"
                />
              ) : (
                <div className="w-full h-full flex items-center justify-center bg-gray-200 text-4xl text-gray-600 font-semibold">
                  {userProfile.name?.charAt(0) || '?'}
                </div>
              )}
            </div>
            
            <div className="flex-1 text-center md:text-left">
              <h1 className="text-2xl font-bold">{userProfile.name}</h1>
              <p className="text-gray-600">{userProfile.email}</p>
              
              {userProfile.location && (
                <p className="mt-2 text-sm text-gray-500 flex items-center justify-center md:justify-start">
                  <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17.657 16.657L13.414 20.9a1.998 1.998 0 01-2.827 0l-4.244-4.243a8 8 0 1111.314 0z" />
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 11a3 3 0 11-6 0 3 3 0 016 0z" />
                  </svg>
                  {userProfile.location}
                </p>
              )}

              {userProfile.jobTitle && (
                <p className="mt-1 text-sm text-gray-500">
                  {userProfile.jobTitle}
                </p>
              )}
            </div>
          </div>

          {/* 详细信息 */}
          <div className="mt-8 grid gap-6">
            {userProfile.bio && (
              <div>
                <h2 className="font-semibold text-lg mb-2">个人简介</h2>
                <p className="text-gray-600">{userProfile.bio}</p>
              </div>
            )}
            
            {/* 技能标签 */}
            {userProfile.skills && userProfile.skills.length > 0 && (
              <div>
                <h2 className="font-semibold text-lg mb-2">技能</h2>
                <div className="flex flex-wrap gap-2">
                  {userProfile.skills.map((skill, index) => (
                    <span key={index} className="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-sm">
                      {skill}
                    </span>
                  ))}
                </div>
              </div>
            )}
            
            {/* 社交链接 */}
            {userProfile.socialLinks && Object.keys(userProfile.socialLinks).length > 0 && (
              <div>
                <h2 className="font-semibold text-lg mb-2">社交链接</h2>
                <div className="flex flex-wrap gap-4">
                  {Object.entries(userProfile.socialLinks).map(([key, value]) => 
                    value ? (
                      <a
                        key={key}
                        href={value.startsWith('http') ? value : `https://${value}`}
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-blue-600 hover:underline flex items-center"
                      >
                        {key}
                      </a>
                    ) : null
                  )}
                </div>
              </div>
            )}
            
            {/* 主题颜色选择器 */}
            <div>
              <h2 className="font-semibold text-lg mb-2">个性化</h2>
              <div className="flex flex-col space-y-4">
                <button
                  onClick={() => setShowThemeSelector(!showThemeSelector)}
                  className="inline-flex items-center px-4 py-2 text-sm border border-gray-300 rounded-md hover:bg-gray-50"
                >
                  <SwatchIcon className="h-5 w-5 mr-2" style={{ color: `var(--primary-color)` }} />
                  <span>主题颜色设置</span>
                </button>
                
                {showThemeSelector && (
                  <Card highlight themeBg className="p-4">
                    {themeMessage.text && (
                      <div className={`mb-4 p-2 rounded text-sm ${
                        themeMessage.type === 'success' 
                          ? 'bg-green-50 text-green-700 border-l-4 border-green-500' 
                          : themeMessage.type === 'error' 
                            ? 'bg-red-50 text-red-700 border-l-4 border-red-500' 
                            : ''
                      }`}>
                        {themeMessage.text}
                      </div>
                    )}
                    <p className="text-sm text-gray-600 mb-3">选择您喜欢的主题颜色，立即生效并自动保存</p>
                    <ThemeSelector 
                      selectedColor={themeColor} 
                      onChange={handleThemeColorChange}
                      className="max-w-sm"
                      showLabels
                      size="md"
                    />
                    {savingTheme && (
                      <div className="mt-2 text-sm text-gray-500">保存中...</div>
                    )}
                  </Card>
                )}
              </div>
            </div>
          </div>

          {/* 编辑按钮 */}
          <div className="mt-8 flex justify-end">
            <button
              onClick={() => setIsProfileDialogOpen(true)}
              className="inline-flex items-center px-4 py-2 border border-gray-300 shadow-sm text-sm font-medium rounded-md text-gray-700 bg-white hover:bg-gray-50 focus:outline-none"
            >
              <UserIcon className="h-4 w-4 mr-2" />
              编辑资料
            </button>
          </div>
        </div>
      </div>

      {/* 个人资料编辑对话框 */}
      <ProfileDialog 
        isOpen={isProfileDialogOpen}
        onClose={() => setIsProfileDialogOpen(false)}
        profile={userProfile}
        onSave={handleSaveProfile}
      />
    </div>
  );
} 